package com.leetcode.partition9;

/**
 * @author `RKC`
 * @date 2021/9/4 9:22
 */
public class LC860柠檬水找零 {

    public static boolean lemonadeChange(int[] bills) {
        return greedy(bills);
    }

    public static void main(String[] args) {
        int[] bills = {5, 5, 10, 10, 20};
        System.out.println(lemonadeChange(bills));
    }

    private static boolean greedy(final int[] bills) {
        if (bills[0] > 5) return false;
        int fiveCount = 0, tenCount = 0, twentyCount = 0;
        for (int i = 0; i < bills.length; i++) {
            if (bills[i] == 5) fiveCount++;         //5元直接收下
            else if (bills[i] == 10) {              //找回5元，收下10元
                if (fiveCount < 1) return false;
                fiveCount--;
                tenCount++;
            } else if (bills[i] == 20) {
                boolean flag = false;
                //优先考虑找回10+5，如果没有10，再考虑找回5+5+5
                if (tenCount >= 1 && fiveCount >= 1) {
                    twentyCount++;
                    tenCount--;
                    fiveCount--;
                    flag = true;
                } else if (tenCount == 0 && fiveCount >= 3) {
                    fiveCount -= 3;
                    twentyCount++;
                    flag = true;
                }
                if (!flag) return false;
            }
        }
        return true;
    }
}
